//
//  PPWebGrabImagesViewController.m
//  pickpic
//
//  Created by Jinxiao on 10/10/16.
//  Copyright © 2016 MicroDream. All rights reserved.
//

#import "PPWebGrabImagesViewController.h"
#import "PPAlbumContentViewDataSource.h"
#import "PPAlbumPictureInsertionViewController.h"
#import "PPAssetsPictureViewController.h"

@interface PPWebGrabImagesViewController () <PPAssetsPictureViewControllerDelegate>
@property (readwrite, nonatomic, assign) BOOL loaded;
@property (readwrite, nonatomic, strong) NSError *error;
@end

@implementation PPWebGrabImagesViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    __weak typeof(self)weakSelf = self;
    [self setNavigationRightTitle:@"确定" action:^{
        [weakSelf confirmSelection];
    }];

    [self setNavigationLefeImage:[UIImage imageNamed:@"return"] action:^{
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];

    [self layoutSelections];

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];
    hud.mode = MBProgressHUDModeIndeterminate;
    hud.labelText = @"Loading...";
    hud.labelFont = [UIFont boldSystemFontOfSize:18];

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)((arc4random()%10/10.0 + 1) * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if(_URLStrings.count == 0) {
            [self didFinishGrabbingWithURLStrings:nil error:[NSError errorWithDomain:NSURLErrorDomain code:0 userInfo:nil]];
        } else {
            [self didFinishGrabbingWithURLStrings:_URLStrings error:nil];
        }
    });
}

- (void)confirmSelection {
    [MobClick event:@"管理-抓取第一步-确认-点击确认"];
    NSMutableArray *selectedItems = [NSMutableArray array];

    for(PPImageFlowItem *item in self.items) {
        if(item.selected) {
            [selectedItems addObject:item];
        }
    }

    if(selectedItems.count == 0) {
        [self.view toastMessage:@"请选择至少一张图片"];
    } else {
        PPAlbumContentViewDataSource *dataSource = [[PPAlbumContentViewDataSource alloc] init];

        for(PPImageFlowItem *item in selectedItems) {
            PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
            artwork.uuid = [NSString uuid];
            artwork.image = item.image;
            artwork.URLString = item.URLString;
            [dataSource.images addObject:artwork];
            [dataSource.insertedImages addObject:artwork];
        }

        PPAlbumPictureInsertionViewController *insertionViewController = [[UIStoryboard storyboardWithName:@"Album" bundle:nil] instantiateViewControllerWithIdentifier:@"PPAlbumPictureInsertionViewController"];
        insertionViewController.dataSource = dataSource;
        [self.navigationController pushViewController:insertionViewController animated:YES];
    }
}

- (void)layoutSelections {

    BOOL selected = NO;

    for(PPImageFlowItem *item in self.items) {
        if(item.selected) {
            selected = YES;
            break;
        }
    }

    UIBarButtonItem *saveItem = self.navigationItem.rightBarButtonItem;

    saveItem.enabled = selected;
}

- (void)didFinishGrabbingWithURLStrings:(NSArray *)URLStrings error:(NSError *)error {
    _loaded = YES;
    _error = error;

    NSMutableArray *items = [NSMutableArray array];

    for(id object in URLStrings) {

        PPImageFlowItem *item = [[PPImageFlowItem alloc] init];

        if([object isKindOfClass:[UIImage class]]) {
            item.image = object;
        } else if([object isKindOfClass:[NSString class]]) {
            NSString *URLString = object;
            NSString *validatedURLString = nil;

            if([URLString hasPrefix:@"http://"] || [URLString hasPrefix:@"https://"]) {
                validatedURLString = URLString;
            } else if([URLString hasPrefix:@"//"]) {
                validatedURLString = [@"http:" stringByAppendingString:URLString];
            } else {
                validatedURLString = [@"http://" stringByAppendingString:URLString];
            }

            item.URLString = validatedURLString;
        }

        [items addObject:item];
    }

    self.items = items;

    [self reloadData];

    [MBProgressHUD hideAllHUDsForView:self.navigationController.view animated:YES];
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(!_loaded) {
        return nil;
    }

    UILabel *label = [[UILabel alloc] init];
    label.text = @"图片抓取失败";
    label.font = [UIFont systemFontOfSize:14];
    label.textColor = [UIColor colorWithRGBHex:0x999999];
    [label sizeToFit];

    return label;
}

- (void)selectedItemsDidChanged {
    [self layoutSelections];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    PPAssetsPictureViewController *pictureViewController = [[PPAssetsPictureViewController alloc] init];
    pictureViewController.delegate = self;

    NSMutableArray *artworks = [NSMutableArray array];

    for(PPImageFlowItem *item in self.items) {
        PPAbstractArtwork *artwork = [[PPAbstractArtwork alloc] init];
        artwork.URLString = item.URLString;
        [artworks addObject:artwork];
    }

    NSInteger index = indexPath.row;

    pictureViewController.index = index;
    pictureViewController.artworks = artworks;

    [self.navigationController pushViewController:pictureViewController animated:YES];
}


#pragma mark - PPAssetsPictureViewControllerDelegate

- (void)pictureViewController:(PPAssetsPictureViewController *)pictureViewController didChangeSelectionOfItemAtIndex:(NSInteger)index {
    PPImageFlowItem *item = [self.items safeObjectAtIndex:index];

    item.selected = !item.selected;

    [self.collectionView reloadData];
}

- (BOOL)pictureViewController:(PPAssetsPictureViewController *)pictureViewController selectionStatusForItemAtIndex:(NSInteger)index {
    PPImageFlowItem *item = [self.items safeObjectAtIndex:index];

    return item.selected;
}

- (NSInteger)numberOfSelectionsForPictureViewController:(PPAssetsPictureViewController *)pictureViewController {
    NSInteger count = 0;

    for(PPImageFlowItem *item in self.items) {
        if(item.selected) {
            count++;
        }
    }

    return count;
}

- (void)pictureViewControllerDidConfirmed:(PPAssetsPictureViewController *)pictureViewController {
    [self confirmSelection];
}

@end
